package com.ruoyi.web.controller.system;

import java.util.Iterator;
import java.util.List;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysClasses;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysClassesService;

/**
 * 班级信息
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/system/classes")
public class SysClassesController extends BaseController
{
    @Autowired
    private ISysClassesService classesService;

    /**
     * 获取班级列表
     */
    @PreAuthorize("@ss.hasPermi('system:classes:list')")
    @GetMapping("/list")
    public AjaxResult list(SysClasses classes)
    {
        List<SysClasses> classess = classesService.selectClassesList(classes);
        return AjaxResult.success(classess);
    }

    /**
     * 查询班级列表（排除节点）
     */
    @PreAuthorize("@ss.hasPermi('system:classes:list')")
    @GetMapping("/list/exclude/{classesId}")
    public AjaxResult excludeChild(@PathVariable(value = "classesId", required = false) Long classesId)
    {
        List<SysClasses> classess = classesService.selectClassesList(new SysClasses());
        Iterator<SysClasses> it = classess.iterator();
        while (it.hasNext())
        {
            SysClasses d = (SysClasses) it.next();
            if (d.getClassesId().intValue() == classesId
                    || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), classesId + ""))
            {
                it.remove();
            }
        }
        return AjaxResult.success(classess);
    }

    /**
     * 根据班级编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:classes:query')")
    @GetMapping(value = "/{classesId}")
    public AjaxResult getInfo(@PathVariable Long classesId)
    {
        classesService.checkClassesDataScope(classesId);
        return AjaxResult.success(classesService.selectClassesById(classesId));
    }

    /**
     * 获取班级下拉树列表
     */
    @GetMapping("/treeselect")
    public AjaxResult treeselect(SysClasses classes)
    {
        List<SysClasses> classess = classesService.selectClassesList(classes);
        return AjaxResult.success(classesService.buildClassesTreeSelect(classess));
    }

    /**
     * 加载对应角色班级列表树
     */
    @GetMapping(value = "/roleClassesTreeselect/{roleId}")
    public AjaxResult roleClassesTreeselect(@PathVariable("roleId") Long roleId)
    {
        List<SysClasses> classess = classesService.selectClassesList(new SysClasses());
        AjaxResult ajax = AjaxResult.success();
        ajax.put("checkedKeys", classesService.selectClassesListByRoleId(roleId));
        ajax.put("classess", classesService.buildClassesTreeSelect(classess));
        return ajax;
    }

    /**
     * 新增班级
     */
    @PreAuthorize("@ss.hasPermi('system:classes:add')")
    @Log(title = "班级管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysClasses classes)
    {
        if (UserConstants.NOT_UNIQUE.equals(classesService.checkClassesNameUnique(classes)))
        {
            return AjaxResult.error("新增班级'" + classes.getClassesName() + "'失败，班级名称已存在");
        }
        classes.setCreateBy(getUsername());
        return toAjax(classesService.insertClasses(classes));
    }

    /**
     * 修改班级
     */
    @PreAuthorize("@ss.hasPermi('system:classes:edit')")
    @Log(title = "班级管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysClasses classes)
    {
        if (UserConstants.NOT_UNIQUE.equals(classesService.checkClassesNameUnique(classes)))
        {
            return AjaxResult.error("修改班级'" + classes.getClassesName() + "'失败，班级名称已存在");
        }
        else if (classes.getParentId().equals(classes.getClassesId()))
        {
            return AjaxResult.error("修改班级'" + classes.getClassesName() + "'失败，上级班级不能是自己");
        }
        else if (StringUtils.equals(UserConstants.DEPT_DISABLE, classes.getStatus())
                && classesService.selectNormalChildrenClassesById(classes.getClassesId()) > 0)
        {
            return AjaxResult.error("该班级包含未停用的子班级！");
        }
        classes.setUpdateBy(getUsername());
        return toAjax(classesService.updateClasses(classes));
    }

    /**
     * 删除班级
     */
    @PreAuthorize("@ss.hasPermi('system:classes:remove')")
    @Log(title = "班级管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{classesId}")
    public AjaxResult remove(@PathVariable Long classesId)
    {
        if (classesService.hasChildByClassesId(classesId))
        {
            return AjaxResult.error("存在下级班级,不允许删除");
        }
        if (classesService.checkClassesExistUser(classesId))
        {
            return AjaxResult.error("班级存在用户,不允许删除");
        }
        return toAjax(classesService.deleteClassesById(classesId));
    }
}
